# -*- encoding: utf-8 -*-

"""
------------------------------------------
@File       : deal_pic_with_queue.py
@Author     : maixiaochai
@Email      : maixiaochai@outlook.com
@CreatedOn  : 2021/6/15 13:36
------------------------------------------
"""
from collections import deque
from queue import Queue
from threading import Lock, Thread
from time import sleep


class PicsQueue:
    def __init__(self):
        self.items = deque()
        self.lock = Lock()

    def put(self, item):
        """
         将新的 item添加到队列的末端
        """
        with self.lock:
            self.items.append(item)

    def get(self):
        """
         从顶部移除item
        """
        with self.lock:
            return self.items.popleft()


class Worker(Thread):
    def __init__(self, func, in_queue, out_queue):
        super().__init__()
        self.func = func
        self.in_queue = in_queue
        self.out_queue = out_queue
        self.polled_count = 0
        self.work_done = 0

    def run(self):
        while True:
            self.polled_count += 1
            try:
                item = self.in_queue.get()
            except IndexError:
                sleep(0.01)

            # 当没有异常发生时，else中的语句将会被执行
            else:
                result = self.func(item)
                self.out_queue.put(result)
                self.work_done += 1


def download(d):
    sleep(0.1)
    return "downloaded"


def resize(r):
    sleep(0.1)
    return "resized"


def upload(u):
    sleep(0.2)
    return "uploaded"


def main():
    download_queue = PicsQueue()
    resize_queue = PicsQueue()
    upload_queue = PicsQueue()
    done_queue = PicsQueue()

    threads = [
        Worker(download, download_queue, resize_queue),
        Worker(resize, resize_queue, upload_queue),
        Worker(upload, upload_queue, done_queue),
    ]

    download_number = 1000
    for thread in threads:
        thread.start()

    for _ in range(download_number):
        download_queue.put(object())

    while len(done_queue.items) % 100 == 0:
        print(
            f"[{len(done_queue.items)}/{download_number}: {round(len(done_queue.items) / download_number * 1000, 2)}%]")


def numbers(item):
    items = [1, 2, 3]

    for i in items:
        try:
            if i == item:
                return
            yield i

        finally:
            print("啊哈")


def demo():
    """
        1
        啊哈
        2
        啊哈
        啊哈
    """
    data = numbers(3)
    print(next(data))
    print(next(data))
    print(next(data))


if __name__ == '__main__':
    # main()
    demo()
